package com.dbms.service;

import com.dbms.domain.vo.DataObject;
import com.dbms.utils.ExcelParser;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.usermodel.*;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

@Service
@RequiredArgsConstructor
public class GenericExcelImportService {

    final ExcelParser excelParser;

    public List<DataObject> importExcel(MultipartFile file) throws IOException {
        // 将 MultipartFile 转换为 File
        File tempFile = File.createTempFile("temp", file.getOriginalFilename());
        file.transferTo(tempFile);
        try {
            return excelParser.parseExcel(tempFile);
        } finally {
            // 删除临时文件
            tempFile.delete();
        }
    }

    private String getCellValueAsString(Cell cell) {
        return switch (cell.getCellType()) {
            case STRING -> cell.getStringCellValue();
            case NUMERIC -> cell.getNumericCellValue() + "";
            case BOOLEAN -> cell.getBooleanCellValue() + "";
            case FORMULA -> cell.getCellFormula();
            default -> "";
        };
    }
}
